/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.WebIDE.ejb.sessions;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.transaction.UserTransaction;
import org.WebIDE.ejb.entities.*;
import org.WebIDE.ejb.sessions.exceptions.*;

/**
 *
 * @author huy
 */
@Stateless
public class GroupsFacade implements GroupsFacadeLocal, GroupsFacadeRemote {
    @Resource
    private UserTransaction utx = null;
    @PersistenceContext(unitName = "WebIDE-ejbPU")
    private EntityManager _em;
    @PersistenceUnit(unitName = "WebIDE-ejbPU")
    private EntityManagerFactory emf = null;
/*
    public void create(Groups groups) {
        _em.persist(groups);
    }

    public void edit(Groups groups) {
        _em.merge(groups);
    }
*/
    public void remove(Groups groups) {
        _em.remove(_em.merge(groups));
    }

    public Groups find(Object id) {
        return _em.find(Groups.class, id);
    }

    public List<Groups> findAll() {
        return _em.createQuery("select object(o) from Groups as o").getResultList();
    }
    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Groups groups) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (groups.getUsersCollection() == null) {
            groups.setUsersCollection(new ArrayList<Users>());
        }
        EntityManager em = null;
        try {
            //utx.begin();
            em = getEntityManager();
            Collection<Users> attachedUserNameCollection = new ArrayList<Users>();
            for (Users userNameCollectionUsersToAttach : groups.getUsersCollection()) {
                userNameCollectionUsersToAttach = em.getReference(userNameCollectionUsersToAttach.getClass(), userNameCollectionUsersToAttach.getUserName());
                attachedUserNameCollection.add(userNameCollectionUsersToAttach);
            }
            groups.setUsersCollection(attachedUserNameCollection);
            em.persist(groups);
            for (Users userNameCollectionUsers : groups.getUsersCollection()) {
                userNameCollectionUsers.getGroupsCollection().add(groups);
                userNameCollectionUsers = em.merge(userNameCollectionUsers);
            }
            //utx.commit();
        } catch (Exception ex) {
            try {
                //utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findGroups(groups.getGroupName()) != null) {
                throw new PreexistingEntityException("Groups " + groups + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Groups groups) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            //utx.begin();
            em = getEntityManager();
            Groups persistentGroups = em.find(Groups.class, groups.getGroupName());
            Collection<Users> userNameCollectionOld = persistentGroups.getUsersCollection();
            Collection<Users> userNameCollectionNew = groups.getUsersCollection();
            Collection<Users> attachedUserNameCollectionNew = new ArrayList<Users>();
            for (Users userNameCollectionNewUsersToAttach : userNameCollectionNew) {
                userNameCollectionNewUsersToAttach = em.getReference(userNameCollectionNewUsersToAttach.getClass(), userNameCollectionNewUsersToAttach.getUserName());
                attachedUserNameCollectionNew.add(userNameCollectionNewUsersToAttach);
            }
            userNameCollectionNew = attachedUserNameCollectionNew;
            groups.setUsersCollection(userNameCollectionNew);
            groups = em.merge(groups);
            for (Users userNameCollectionOldUsers : userNameCollectionOld) {
                if (!userNameCollectionNew.contains(userNameCollectionOldUsers)) {
                    userNameCollectionOldUsers.getGroupsCollection().remove(groups);
                    userNameCollectionOldUsers = em.merge(userNameCollectionOldUsers);
                }
            }
            for (Users userNameCollectionNewUsers : userNameCollectionNew) {
                if (!userNameCollectionOld.contains(userNameCollectionNewUsers)) {
                    userNameCollectionNewUsers.getGroupsCollection().add(groups);
                    userNameCollectionNewUsers = em.merge(userNameCollectionNewUsers);
                }
            }
            //utx.commit();
        } catch (Exception ex) {
            try {
                //utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = groups.getGroupName();
                if (findGroups(id) == null) {
                    throw new NonexistentEntityException("The groups with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            //utx.begin();
            em = getEntityManager();
            Groups groups;
            try {
                groups = em.getReference(Groups.class, id);
                groups.getGroupName();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The groups with id " + id + " no longer exists.", enfe);
            }
            Collection<Users> userNameCollection = groups.getUsersCollection();
            for (Users userNameCollectionUsers : userNameCollection) {
                userNameCollectionUsers.getGroupsCollection().remove(groups);
                userNameCollectionUsers = em.merge(userNameCollectionUsers);
            }
            em.remove(groups);
            //utx.commit();
        } catch (Exception ex) {
            try {
                //utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Groups> findGroupsEntities() {
        return findGroupsEntities(true, -1, -1);
    }

    public List<Groups> findGroupsEntities(int maxResults, int firstResult) {
        return findGroupsEntities(false, maxResults, firstResult);
    }

    private List<Groups> findGroupsEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Groups as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Groups findGroups(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Groups.class, id);
        } finally {
            em.close();
        }
    }

    public int getGroupsCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Groups as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
